import 'package:dio/dio.dart';
import 'package:get_it/get_it.dart';
import 'package:flutter/foundation.dart';
import 'package:provider/provider.dart';

import '../../core/constants/api_constants.dart';
import '../../domain/services/upload_service.dart';
import '../../domain/services/upload_task_factory.dart';
import '../../domain/providers/upload_queue_provider.dart';
import '../../domain/providers/auth_provider.dart';
import '../../domain/providers/backup_provider.dart';
import '../../domain/providers/album_provider.dart';
import '../../domain/services/album_cache_service.dart';
import '../../core/exceptions/app_exception.dart';

/// 全局依赖注入管理器
final GetIt serviceLocator = GetIt.instance;

/// 认证拦截器
class AuthInterceptor extends Interceptor {
  final AuthProvider authProvider;
  final Dio dio;
  bool _isRefreshing = false;
  final List<RequestOptions> _pendingRequests = [];

  AuthInterceptor(this.authProvider, this.dio);

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    if (authProvider.isAuthenticated && authProvider.accessToken != null) {
      options.headers['Authorization'] = 'Bearer ${authProvider.accessToken}';
      debugPrint('添加认证令牌到请求: ${options.uri}');
    } else {
      debugPrint('请求未认证: ${options.uri}');
    }
    return super.onRequest(options, handler);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) async {
    // 检查是否是认证错误
    if (err.response?.statusCode == 401) {
      debugPrint('收到401错误，尝试刷新令牌');

      if (_isRefreshing) {
        // 如果正在刷新中，将请求添加到等待队列
        _pendingRequests.add(err.requestOptions);
        debugPrint('令牌刷新中，将请求添加到等待队列');
        return;
      }

      // 锁定标记，防止多次刷新
      _isRefreshing = true;

      try {
        // 尝试刷新令牌
        await authProvider.refreshToken();
        debugPrint('令牌刷新成功，重新发送请求');

        // 重新发送请求
        final response = await _retry(err.requestOptions);

        // 处理等待队列中的请求
        _resolvePendingRequests();

        // 通知处理器请求已成功
        handler.resolve(response);
      } catch (e) {
        debugPrint('令牌刷新失败: $e');
        // 尝试所有等待请求，让它们也失败
        _rejectPendingRequests();

        // 如果是令牌刷新失败，通常需要用户重新登录
        if (e is TokenExpiredException) {
          debugPrint('令牌已过期，需要重新登录');
          // 此处可以触发导航到登录页面
          // 或者直接清除认证状态
          authProvider.logout();
        }

        // 继续向上抛出错误
        handler.next(err);
      } finally {
        _isRefreshing = false;
      }
    } else {
      // 其他错误直接向上抛出
      handler.next(err);
    }
  }

  // 重新发送请求
  Future<Response> _retry(RequestOptions requestOptions) async {
    final options = Options(
      method: requestOptions.method,
      headers: {
        ...requestOptions.headers,
        'Authorization': 'Bearer ${authProvider.accessToken}',
      },
    );

    return dio.request<dynamic>(
      requestOptions.path,
      data: requestOptions.data,
      queryParameters: requestOptions.queryParameters,
      options: options,
    );
  }

  // 处理等待队列中的请求
  void _resolvePendingRequests() {
    for (final requestOptions in _pendingRequests) {
      dio.fetch(
        requestOptions
          ..headers['Authorization'] = 'Bearer ${authProvider.accessToken}',
      );
    }
    _pendingRequests.clear();
  }

  // 拒绝所有等待的请求
  void _rejectPendingRequests() {
    // 仅清空等待队列，这些请求会在超时后自动失败
    debugPrint('清空${_pendingRequests.length}个等待的请求');
    _pendingRequests.clear();
  }
}

/// 初始化依赖注入
Future<void> setupServiceLocator() async {
  // Dio网络客户端
  final dio = Dio(
    BaseOptions(
      baseUrl: ApiConstants.baseUrl,
      connectTimeout: Duration(seconds: ApiConstants.timeout),
      receiveTimeout: Duration(seconds: ApiConstants.timeout),
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      },
      validateStatus: (status) => status! < 500, // 不将4xx状态码视为错误，让拦截器处理
    ),
  );

  // 注册网络拦截器
  dio.interceptors.add(LogInterceptor(requestBody: true, responseBody: true));

  // 注册服务
  serviceLocator.registerLazySingleton<Dio>(() => dio);
  serviceLocator.registerLazySingleton<UploadService>(
    () => UploadService(serviceLocator<Dio>()),
  );

  // 注册相册缓存服务
  serviceLocator.registerLazySingleton<AlbumCacheService>(
    () => AlbumCacheService(),
  );

  // 注册工厂
  serviceLocator.registerFactory(() => UploadTaskFactory());

  // 注册状态管理器
  serviceLocator.registerLazySingleton<UploadQueueProvider>(
    () => UploadQueueProvider(serviceLocator<UploadService>()),
  );

  // 注册备份设置状态管理器
  serviceLocator.registerLazySingleton<BackupProvider>(() => BackupProvider());

  // 注册相册管理状态管理器
  serviceLocator.registerLazySingleton<AlbumProvider>(
    () => AlbumProvider(cacheService: serviceLocator<AlbumCacheService>()),
  );
}

/// 设置认证拦截器
void setupAuthInterceptor(AuthProvider authProvider) {
  final dio = serviceLocator<Dio>();
  dio.interceptors.add(AuthInterceptor(authProvider, dio));
}
